package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video/models/mysql"
	"video/pkg"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var FindUser mysql.User
	err := FindUser.FindUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if FindUser.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}
	if len(in.Phone) != 11 {
		return nil, errors.New("手机号码必须为11位数")
	}
	user := &mysql.User{
		Phone:      in.Phone,
		Password:   pkg.Md5(in.Password),
		NickName:   fmt.Sprintf("用户_%d", rand.Intn(10000)),
		AvatarLink: "http://t4kawq9ae.hn-bkt.clouddn.com.jpg",
	}
	err = user.UserAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("注册失败")
	}

	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
